﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace TextRpgXNA
{
    class QuadTree
    {
        private QuadTreeNode head;

        public QuadTree(List<IWorldObject> worldItems, Point minimum, Point maximum) : this(worldItems, minimum.X, minimum.Y, maximum.X, maximum.Y) { }

        public QuadTree(List<IWorldObject> worldItems, int minimumWidth, int minimumHeight, int maximumWidth, int maximumHeight)
        {
            Point quadStart;
            Point quadEnd;
            int comparer = 1;
            if (maximumWidth - minimumWidth > maximumHeight - minimumHeight)
            {
                comparer = maximumWidth - minimumWidth;
            }
            else
            {
                comparer = maximumHeight - minimumHeight;
            }

            int multiple = 1;
            while (true)
            {
                if (comparer > multiple)
                {
                    multiple *= 2;
                }
                else
                {
                    break;
                }
            }

            quadStart = new Point(minimumWidth, minimumHeight);
            quadEnd = new Point(minimumWidth + multiple, minimumHeight + multiple);

            head = new QuadTreeNode(quadStart, quadEnd);
            int temp = 0;
                foreach (IWorldObject i in worldItems)
                {
                    if (i.Collidable)
                    {
                        temp++;
                        head.Update(i.Location, true);
                        System.Diagnostics.Trace.WriteLine("" + temp);
                    }
                }
            
        }


        public void Update(List<IWorldDynamicObject> worldItems)
        {
            foreach (IWorldDynamicObject item in worldItems)
            {
                    if (!item.Location.Equals(item.PrevLocation))
                    {
                        head.Update(item.Location, true);
                        head.Update(item.PrevLocation, false);
                        item.PrevLocation = item.Location;
                    }
                
            }
        }

        public void UpdateSingle(IWorldDynamicObject dynamicItem)
        {
            if (!dynamicItem.Location.Equals( dynamicItem.PrevLocation))
                    {
                        head.Update(dynamicItem.PrevLocation, false);
                        head.Update( dynamicItem.Location, true);
                         dynamicItem.PrevLocation =  dynamicItem.Location;
                    }
        }

        public bool Search(LocationPair pair)
        {
            return head.search(pair);
        }

    }
}
